package com.doudou.dubbo.samples.detail.service;

import com.doudou.dubbo.samples.comment.api.CommentService;
import com.doudou.dubbo.samples.detail.api.DetailService;
import com.doudou.dubbo.samples.detail.po.Item;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;

/**
 * @author admin
 */
@DubboService
public class DetailServiceImplGray implements DetailService {

    @DubboReference(check = false)
    private CommentService commentService;

    @Override
    public Item getItem(long sku, String username) {
        RpcContext.getClientAttachment().setAttachment("dubbo.tag", "gray");
        return getItem(sku);
    }

    @Override
    public boolean deductStock(long sku, int count) {
        try {
            // Do something that consumes resources
            for (int i = 0; i < 500; i++) {
                Math.pow(ThreadLocalRandom.current().nextDouble(10), ThreadLocalRandom.current().nextDouble(5));
            }
            Thread.sleep(ThreadLocalRandom.current().nextInt(50));
        } catch (InterruptedException ignore) {
            Thread.currentThread().interrupt();
        }
        return true;
    }

    private Item getItem(long sku) {
        Item item = new Item();
        item.setSku(sku);
        item.setItemName("itemName");
        item.setDescription("item from detail gray");
        item.setStock(100);
        item.setPrice(100);
        item.setComment(commentService.getComment("itemName"));
        return item;
    }

}
